﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using SportStore.Models.Concrete;
using SportStore.Models.Abstract;
using SportStore.Models.Entities;
using System.IO;
using System.Drawing;
using System.Data.Objects;
using System.Data.Entity;
using SportStore.Models;
using SportStore.Filters;

namespace SportStore.Controllers
{
    public class AdminController : Controller
    {
        private IRepository repository = new EFRepository();
        [RoleFilter(AuthorizedRoles=new string[] {"admin","user"})]
        public ViewResult Index()
        {
            return View(repository.Products);
        }

        public ViewResult CategoriesIndex()
        {
            return View(repository.Categories);
        }

        public ViewResult Create()
        {
            ViewBag.PossibleCategories = repository.Categories;
            return View("Edit", new ProductViewModel());
        }

        public ViewResult CreateCategory()
        {
            return View("EditCategory", new Category());
        }

        #region Delete
        public ActionResult Delete(int? id)
        {
            Product prod = repository.Products.FirstOrDefault(p => p.ProductID == id);
            if (prod != null)
            {
                repository.DeleteProduct(prod);
                TempData["message"] = string.Format("{0} was deleted", prod.Name);
            }
            return RedirectToAction("Index");
        }

        public ActionResult DeleteCategory(int? id)
        {
            Category cat = repository.Categories.FirstOrDefault(c => c.CategoryID == id);
            if (cat != null)
            {
                repository.DeleteCategory(cat);
                TempData["message"] = string.Format("{0} was deleted", cat.Name);
            }
            return RedirectToAction("CategoriesIndex");
        }
        #endregion

        bool abrt()
        {
            return false;
        }
        #region Edit product
        [RoleFilter(AuthorizedRoles = new string[] { "admin" }, RequestKey = "ProductId")]
        [HttpPost]
        public ActionResult Edit(ProductViewModel productViewModel, HttpPostedFileBase image)
        {
            Product product = null;
            if (productViewModel.ProductId != 0)
                product = repository.Products.FirstOrDefault(p => p.ProductID == productViewModel.ProductId);
            else
                product = new Product();
            productViewModel.fillThisModel(product,id=>repository.Categories.FirstOrDefault(c=>c.CategoryID == id));
            if (ModelState.IsValid)
            {
                byte[] ImageData =null;
                string filePath=null; 
                if (image != null)
                {
                    ImageData = new byte[image.ContentLength];
                    filePath = System.Web.HttpContext.Current.Server.MapPath("/") + "\\Images\\" + image.FileName;
                    product.ImageMimeType = image.ContentType;
                    product.ImageFileName = "/Images/" + image.FileName;
                    image.InputStream.Read(ImageData, 0, image.ContentLength);
                    FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate);
                    fs.Write(ImageData, 0, ImageData.Length);
                    fs.Close();
                    Bitmap b = new Bitmap(filePath);
                    double perc = 75.0 / b.Height;
                    int w = (int)(b.Width * perc);
                    Image thumb = b.GetThumbnailImage(w, 75, new Image.GetThumbnailImageAbort(abrt), IntPtr.Zero);
                    string fn = filePath + "thumb";
                    thumb.Save(fn, System.Drawing.Imaging.ImageFormat.Png);
                }
                repository.SaveProduct(product);
                TempData["message"] = string.Format("{0} has been saved", product.Name);
                return RedirectToAction("Index");
            }
            ViewBag.PossibleCategories = repository.Categories;
            return View(productViewModel);
        }

        [RoleFilter(RequestKey="id", AuthorizedRoles = new string[] { "admin" })]
        public ViewResult Edit(int? id)
        {
            Product product = (from p in repository.Products.Include("Category") where p.ProductID == id select p).SingleOrDefault(); //repository.Products.FirstOrDefault(p => p.ProductID == id);
            ProductViewModel productViewModel = new ProductViewModel(product);
            ViewBag.PossibleCategories = repository.Categories;
            return View(productViewModel);
        }
        #endregion

        #region Edit category
        [HttpPost]
        public ActionResult EditCategory(Category categoryViewModel, HttpPostedFileBase image)
        {
            Category category = categoryViewModel;
            //if (categoryViewModel.CategoryID == 0)
                //category = new Category();
            if (ModelState.IsValid)
            {
                byte[] ImageData = null;
                string filePath = null;
                if (image != null)
                {
                    ImageData = new byte[image.ContentLength];
                    filePath = System.Web.HttpContext.Current.Server.MapPath("/") + "\\Images\\" + image.FileName;
                    category.ImageMimeType = image.ContentType;
                    category.ImageFileName = "/Images/" + image.FileName;
                    image.InputStream.Read(ImageData, 0, image.ContentLength);
                    FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate);
                    fs.Write(ImageData, 0, ImageData.Length);
                    fs.Close();
                    Bitmap b = new Bitmap(filePath);
                    double perc = 75.0 / b.Height;
                    int w = (int)(b.Width * perc);
                    Image thumb = b.GetThumbnailImage(w, 75, new Image.GetThumbnailImageAbort(abrt), IntPtr.Zero);
                    string fn = filePath + "thumb";
                    thumb.Save(fn, System.Drawing.Imaging.ImageFormat.Png);
                }
                repository.SaveCategory(category);
                TempData["message"] = string.Format("{0} has been saved", category.Name);
                return RedirectToAction("Index");
            }
            return View(categoryViewModel);
        }

        public ViewResult EditCategory(int? id)
        {

            Category category = repository.Categories.FirstOrDefault(c => c.CategoryID == id);
            return View(category);
        }
        #endregion
    }
}
